const crypto = require('node:crypto');

class Aes {
    encIv?:string;
    constructor(secretIv:string) {
        this.encIv = crypto.createHash('sha512').update(secretIv).digest('hex').substr(0,16);
    }
    encryptData(text:string,passwd:string) {
        const key = crypto.createHash('sha512').update(passwd).digest('hex').substring(0,32)
        const cipher = crypto.createCipheriv('aes-256-cbc', key, this.encIv)
        const encrypted = cipher.update(text, 'utf8', 'hex') + cipher.final('hex')
        return Buffer.from(encrypted).toString('base64')

    }
    decryptData(data:string, passwd:string) {
        const buff = Buffer.from(data, 'base64')
        let encryptedData = buff.toString('utf-8');
        const key = crypto.createHash('sha512').update(passwd).digest('hex').substring(0,32)
        const decipher = crypto.createDecipheriv('aes-256-cbc', key, this.encIv)
        return decipher.update(encryptedData, 'hex', 'utf8') + decipher.final('utf8')
    }
}

function encryptAes(iv:string, text:string, passwd:string) {
    let aes = new Aes(iv);
    return aes.encryptData(text, passwd);
}

function decryptAes(iv:string, text:string, passwd:string) {
    let aes = new Aes(iv);
    return aes.decryptData(text, passwd);
}
export {
    Aes, decryptAes, encryptAes
}
